<template>
  <div class="main">
    <div>
      <img src="~/assets/img/text_logo.png" width="100%" alt="霍森学院">
    </div>
    <div class="title">
      <a class="active no-line" href="/login">登录</a>
      <span>·</span>
      <a class="no-line" href="/register">注册</a>
    </div>

    <div class="sign-up-container">
      <el-form :model="member" status-icon :rules="rules" ref="memberForm">
        <el-form-item prop="username">
          <el-input v-model="member.username"
                    placeholder="用户名"
                    clearable
          >
            <svg-icon slot="prefix" icon-class="user-smile" class="ml5"/>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password"
                    v-model="member.password"
                    placeholder="密码"
                    clearable
                    @keyup.enter.native="submitForm()"
          >
            <svg-icon slot="prefix" icon-class="lock" class="ml5"/>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="submitForm()" style="width: 100%">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import '~/assets/css/sign.css'
import '~/assets/css/iconfont.css'
import cookie from 'js-cookie'
import loginApi from '~/api/login'

export default {
  layout: 'sign',
  data() {
    return {
      member: {
        username: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs.memberForm.validate((valid) => {
        if (valid) {
          this.submitLogin()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 登录
    submitLogin() {
      // 执行远程登录接口调用
      loginApi.login(this.member).then(response => {
        // 将jwt写入cookie
        cookie.set('hsedu_jwt_token', response.data.token, { domain: 'localhost' })
        // 如果上一页是注册页面，则跳转到网站的首页
        if (document.referrer.indexOf('register') !== -1) {
          window.location.href = '/'
        } else {
          // 否则跳转到上一个刚刚访问的页面
          history.go(-1)
        }
      })
    }
  }
}
</script>
